import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  Switch,
  message,
  Popconfirm,
  Card,
  Row,
  Col,
  Tag,
  Tooltip,
  Badge,
  Descriptions,
  Tabs
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ExportOutlined,
  SearchOutlined,
  ReloadOutlined,
  EyeOutlined,
  SendOutlined,
  BarChartOutlined
} from '@ant-design/icons';
import { DeviceApi, DeviceVO, DevicePageParams, DeviceUpdateStatusVO } from '../../../api/iot/device';

const { Option } = Select;
const { TabPane } = Tabs;

const DeviceManagement: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [devices, setDevices] = useState<DeviceVO[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchParams, setSearchParams] = useState<DevicePageParams>({});
  const [modalVisible, setModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [editingDevice, setEditingDevice] = useState<DeviceVO | null>(null);
  const [selectedDevice, setSelectedDevice] = useState<DeviceVO | null>(null);
  const [form] = Form.useForm();

  // 设备状态选项
  const statusOptions = [
    { label: '未激活', value: 0, color: 'default' },
    { label: '在线', value: 1, color: 'success' },
    { label: '离线', value: 2, color: 'error' },
    { label: '故障', value: 3, color: 'warning' }
  ];

  // 获取设备列表
  const fetchDevices = async () => {
    setLoading(true);
    try {
      const params = {
        pageNo: currentPage,
        pageSize,
        ...searchParams
      };
      const response = await DeviceApi.getDevicePage(params);
      setDevices(response.data.list || []);
      setTotal(response.data.total || 0);
    } catch (error) {
      message.error('获取设备列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchDevices();
  }, [currentPage, pageSize, searchParams]);

  // 搜索处理
  const handleSearch = (values: any) => {
    setSearchParams(values);
    setCurrentPage(1);
  };

  // 重置搜索
  const handleReset = () => {
    setSearchParams({});
    setCurrentPage(1);
  };

  // 新增设备
  const handleAdd = () => {
    setEditingDevice(null);
    setModalVisible(true);
    form.resetFields();
  };

  // 编辑设备
  const handleEdit = (record: DeviceVO) => {
    setEditingDevice(record);
    setModalVisible(true);
    form.setFieldsValue(record);
  };

  // 查看设备详情
  const handleViewDetail = (record: DeviceVO) => {
    setSelectedDevice(record);
    setDetailModalVisible(true);
  };

  // 删除设备
  const handleDelete = async (id: number) => {
    try {
      await DeviceApi.deleteDevice(id);
      message.success('删除成功');
      fetchDevices();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 更新设备状态
  const handleUpdateStatus = async (id: number, status: number) => {
    try {
      const updateData: DeviceUpdateStatusVO = { id, status };
      await DeviceApi.updateDeviceStatus(updateData);
      message.success('状态更新成功');
      fetchDevices();
    } catch (error) {
      message.error('状态更新失败');
    }
  };

  // 发送设备命令
  const handleSendCommand = async (deviceId: number, command: string) => {
    try {
      await DeviceApi.sendDeviceCommand(deviceId, command);
      message.success('命令发送成功');
    } catch (error) {
      message.error('命令发送失败');
    }
  };

  // 保存设备
  const handleSave = async (values: DeviceVO) => {
    try {
      if (editingDevice) {
        await DeviceApi.updateDevice({ ...editingDevice, ...values });
        message.success('更新成功');
      } else {
        await DeviceApi.createDevice(values);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchDevices();
    } catch (error) {
      message.error('保存失败');
    }
  };

  // 导出设备
  const handleExport = async () => {
    try {
      await DeviceApi.exportDevice(searchParams);
      message.success('导出成功');
    } catch (error) {
      message.error('导出失败');
    }
  };

  // 获取状态标签
  const getStatusTag = (status: number) => {
    const option = statusOptions.find(opt => opt.value === status);
    return option ? (
      <Badge status={option.color as any} text={option.label} />
    ) : <Badge status="default" text="未知" />;
  };

  // 表格列定义
  const columns = [
    {
      title: '设备名称',
      dataIndex: 'deviceName',
      key: 'deviceName',
      width: 150,
      ellipsis: true
    },
    {
      title: '设备标识',
      dataIndex: 'deviceKey',
      key: 'deviceKey',
      width: 120,
      ellipsis: true
    },
    {
      title: '设备类型',
      dataIndex: 'deviceType',
      key: 'deviceType',
      width: 100,
      ellipsis: true
    },
    {
      title: '产品名称',
      dataIndex: 'productName',
      key: 'productName',
      width: 120,
      ellipsis: true
    },
    {
      title: '设备状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: number) => getStatusTag(status)
    },
    {
      title: '激活状态',
      dataIndex: 'activeTime',
      key: 'activeTime',
      width: 100,
      render: (time: Date) => (
        <Tag color={time ? 'green' : 'red'}>
          {time ? '已激活' : '未激活'}
        </Tag>
      )
    },
    {
      title: '最后上线时间',
      dataIndex: 'lastOnlineTime',
      key: 'lastOnlineTime',
      width: 150,
      render: (time: string) => time ? new Date(time).toLocaleString() : '-'
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
      render: (time: string) => time ? new Date(time).toLocaleString() : '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 250,
      fixed: 'right' as const,
      render: (record: DeviceVO) => (
        <Space>
          <Tooltip title="查看详情">
            <Button
              type="link"
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleViewDetail(record)}
            />
          </Tooltip>
          <Tooltip title="编辑">
            <Button
              type="link"
              size="small"
              icon={<EditOutlined />}
              onClick={() => handleEdit(record)}
            />
          </Tooltip>
          <Tooltip title="发送命令">
            <Button
              type="link"
              size="small"
              icon={<SendOutlined />}
              onClick={() => {
                Modal.confirm({
                  title: '发送设备命令',
                  content: (
                    <Input
                      placeholder="请输入命令内容"
                      onChange={(e) => {
                        const command = e.target.value;
                        if (command) {
                          Modal.destroyAll();
                          handleSendCommand(record.id!, command);
                        }
                      }}
                    />
                  ),
                  okButtonProps: { style: { display: 'none' } },
                  cancelText: '取消'
                });
              }}
            />
          </Tooltip>
          <Popconfirm
            title="确定要删除这个设备吗？"
            onConfirm={() => handleDelete(record.id!)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button
                type="link"
                size="small"
                danger
                icon={<DeleteOutlined />}
              />
            </Tooltip>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <Row gutter={[16, 16]}>
          <Col span={24}>
            <Form
              layout="inline"
              onFinish={handleSearch}
              style={{ marginBottom: '16px' }}
            >
              <Form.Item name="name">
                <Input placeholder="设备名称" />
              </Form.Item>
              <Form.Item name="deviceKey">
                <Input placeholder="设备标识" />
              </Form.Item>
              <Form.Item name="productId">
                <Input placeholder="产品ID" />
              </Form.Item>
              <Form.Item name="status">
                <Select placeholder="设备状态" style={{ width: 120 }} allowClear>
                  {statusOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item>
                <Space>
                  <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                    搜索
                  </Button>
                  <Button onClick={handleReset} icon={<ReloadOutlined />}>
                    重置
                  </Button>
                </Space>
              </Form.Item>
            </Form>
          </Col>
          <Col span={24}>
            <Space style={{ marginBottom: '16px' }}>
              <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                新增设备
              </Button>
              <Button icon={<ExportOutlined />} onClick={handleExport}>
                导出
              </Button>
            </Space>
          </Col>
        </Row>

        <Table
          columns={columns}
          dataSource={devices}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1400 }}
          pagination={{
            current: currentPage,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, size) => {
              setCurrentPage(page);
              setPageSize(size || 10);
            }
          }}
        />
      </Card>

      {/* 新增/编辑设备弹窗 */}
      <Modal
        title={editingDevice ? '编辑设备' : '新增设备'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        width={800}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="deviceName"
                label="设备名称"
                rules={[{ required: true, message: '请输入设备名称' }]}
              >
                <Input placeholder="请输入设备名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="deviceKey"
                label="设备标识"
                rules={[{ required: true, message: '请输入设备标识' }]}
              >
                <Input placeholder="请输入设备标识" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="deviceType"
                label="设备类型"
                rules={[{ required: true, message: '请输入设备类型' }]}
              >
                <Input placeholder="请输入设备类型" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="productId"
                label="产品ID"
                rules={[{ required: true, message: '请输入产品ID' }]}
              >
                <Input placeholder="请输入产品ID" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="status" label="设备状态">
                <Select placeholder="请选择设备状态">
                  {statusOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="activeTime" label="激活状态" valuePropName="checked">
                <Switch checkedChildren="已激活" unCheckedChildren="未激活" />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item name="address" label="备注">
                <Input.TextArea rows={3} placeholder="请输入备注" />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      {/* 设备详情弹窗 */}
      <Modal
        title="设备详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={800}
        destroyOnClose
      >
        {selectedDevice && (
          <Tabs defaultActiveKey="1">
            <TabPane tab="基本信息" key="1">
              <Descriptions bordered column={2}>
                <Descriptions.Item label="设备名称">{selectedDevice.deviceName}</Descriptions.Item>
                <Descriptions.Item label="设备标识">{selectedDevice.deviceKey}</Descriptions.Item>
                <Descriptions.Item label="设备类型">{selectedDevice.deviceType}</Descriptions.Item>
                <Descriptions.Item label="产品名称">{selectedDevice.productName}</Descriptions.Item>
                <Descriptions.Item label="设备状态">
                  {getStatusTag(selectedDevice.status!)}
                </Descriptions.Item>
                <Descriptions.Item label="激活状态">
                  <Tag color={selectedDevice.activeTime ? 'green' : 'red'}>
                    {selectedDevice.activeTime ? '已激活' : '未激活'}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="最后上线时间">
                  {selectedDevice.lastOnlineTime ? new Date(selectedDevice.lastOnlineTime).toLocaleString() : '-'}
                </Descriptions.Item>
                <Descriptions.Item label="创建时间">
                  {selectedDevice.createTime ? new Date(selectedDevice.createTime).toLocaleString() : '-'}
                </Descriptions.Item>
                <Descriptions.Item label="备注" span={2}>
                  {selectedDevice.address || '-'}
                </Descriptions.Item>
              </Descriptions>
            </TabPane>
            <TabPane tab="设备数据" key="2">
              <div style={{ textAlign: 'center', padding: '40px' }}>
                <BarChartOutlined style={{ fontSize: '48px', color: '#ccc' }} />
                <p style={{ color: '#999', marginTop: '16px' }}>暂无设备数据</p>
              </div>
            </TabPane>
            <TabPane tab="操作日志" key="3">
              <div style={{ textAlign: 'center', padding: '40px' }}>
                <p style={{ color: '#999' }}>暂无操作日志</p>
              </div>
            </TabPane>
          </Tabs>
        )}
      </Modal>
    </div>
  );
};

export default DeviceManagement;